package com.mk.utils;

import com.mk.event.MqttMessageEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Component;

/**
 * @author XueJinCha
 */
@Component
@RequiredArgsConstructor
public class MqttUtil {

    private final MessageChannel mqttOutboundChannel;

    private final ApplicationEventPublisher eventPublisher;

    /**
     * 发送消息到默认主题
     *
     * @param payload 消息内容
     */
    public void sendMessage(String payload) {
        mqttOutboundChannel.send(MessageBuilder.withPayload(payload).build());
    }

    /**
     * 发送消息到指定主题
     *
     * @param topic   主题
     * @param payload 消息内容
     */
    public void sendMessage(String topic, String payload) {
        mqttOutboundChannel.send(MessageBuilder.withPayload(payload)
                .setHeader("mqtt_topic", topic)
                .build());
    }

    /**
     * （接收消息:步骤四）发布接收到的MQTT消息事件
     *
     * @param topic   主题
     * @param payload 消息内容
     */
    public void publishReceivedMessage(String topic, String payload) {
        MqttMessageEvent event = new MqttMessageEvent(this, topic, payload);
        eventPublisher.publishEvent(event);
    }
}
